package view
{
	import com.tb.sng.utils.debug.Debug;
	import com.tb.sng.utils.managers.SoundManager;
	import com.tb.sng.utils.managers.WindowManager;
	import com.tb.sng.view.ViewComponent;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.external.ExternalInterface;
	import flash.net.URLVariables;
	import flash.ui.Keyboard;
	import flash.ui.KeyboardType;
	import flash.utils.Timer;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;
	
	import model.UserVo;
	
	import res.WheelMc;
	import res.WinTipMc;
	
	public class WheelView extends ViewComponent
	{
		/**
		 * 轮盘mc 
		 */		
		private var wheel:WheelMc;
		
		/**
		 * 用户信息 
		 */		
		private var userinfo:UserVo;
		
		/**
		 * 返回与游戏信息 
		 */		
		private var info:Object;
		
		/**
		 * 当前左边菜单 
		 */		
		private var leftSprite:Bitmap;
		
		private var betTimer:Timer;
		
		/***********轮盘投注数据***********/
		private var animate_frame:int;
		private var animate_index:int;
		private var speed:int;
		
		private var win:int;
		private var icon:int = -1;
		private var betdata:Object;
		
		/****统计数据*********/
		private var open_icons:Array = [0,0,0, 0,0,0, 0,0];
		private var open_minname:Array = [];// 最近开奖
		
		public function WheelView()
		{
			var i:int;
			
			wheel = new WheelMc();
			userinfo = new UserVo();
			userinfo.reset();
			
			wheel.mc_login.visible = false;
			wheel.mc_uinfo.visible = false;
			
			/**用户登录注册**/
			wheel.mc_login.btn_login.addEventListener(MouseEvent.CLICK, loginHandler);
			wheel.mc_login.btn_register.addEventListener(MouseEvent.CLICK, regHandler);
			wheel.mc_login.ipass.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler);
			
			wheel.mc_login.btn_login.tabEnabled = false;
			wheel.mc_login.btn_register.tabEnabled = false;
			
			wheel.mc_bet.tabEnabled = false;
			wheel.mc_bet.tabChildren = false;
			
			
			wheel.btn_start.tabEnabled = false;
			
			
			wheel.mc_etip.tabEnabled = false;
			wheel.mc_etip.tabChildren = false;
			
			wheel.mc_etip.tabEnabled = false;
			wheel.mc_etip.tabChildren = false;
				
			wheel.mc_login.iuser.tabEnabled = true;
			wheel.mc_login.ipass.tabEnabled = true;
			
				
			wheel.mc_uinfo.btn_logout.addEventListener(MouseEvent.CLICK, logoutHandler);
			wheel.mc_uinfo.btn_pay.addEventListener(MouseEvent.CLICK, payHandler);
			
			// 初始化下注值
			for(i = 0; i<=7; i++){
				wheel.mc_bet['Pet_' + i].text = 0;
				wheel.mc_bet['Bet_' + i].addEventListener(MouseEvent.MOUSE_DOWN, betHandler);
				wheel.mc_wheel['Bet_' + i].addEventListener(MouseEvent.MOUSE_DOWN, betHandler);
				
				wheel.mc_bet['Bet_' + i].addEventListener(MouseEvent.MOUSE_UP, stopbetHandler);
				wheel.mc_wheel['Bet_' + i].addEventListener(MouseEvent.MOUSE_UP, stopbetHandler);
				
				wheel.mc_bet['Bet_' + i].addEventListener(MouseEvent.MOUSE_OUT, stopbetHandler);
				wheel.mc_wheel['Bet_' + i].addEventListener(MouseEvent.MOUSE_OUT, stopbetHandler);
			}
			
			wheel.mc_bet.Bet_close.addEventListener(MouseEvent.CLICK, resetHandler);
			wheel.mc_bet['Betall_1'].addEventListener(MouseEvent.CLICK, betallHandler);
			wheel.mc_bet.Betall_10.addEventListener(MouseEvent.CLICK, betallHandler);
			wheel.mc_bet.Betall_100.addEventListener(MouseEvent.CLICK, betallHandler);
			
			wheel.btn_start.addEventListener(MouseEvent.CLICK, startHandler);
			
			wheel.mc_etip.visible = false;
			
			// 声音
			wheel.mc_music.buttonMode = true;
			wheel.mc_music.tabChildren = false;
			wheel.mc_music.tabEnabled = false;
			wheel.mc_music.addEventListener(MouseEvent.CLICK, musicHandler);
			
			// 左边菜单
			wheel.mc_wheel.mc_btns.mouseChildren = false;
			wheel.mc_wheel.mc_btns.mouseEnabled = false;
			wheel.mc_wheel.tabChildren = false;
			wheel.mc_wheel.tabEnabled = false;
			wheel.mc_wheel.btn_beilv.addEventListener(MouseEvent.CLICK, leftMenuHandler);
			wheel.mc_wheel.btn_times.addEventListener(MouseEvent.CLICK, leftMenuHandler);
			wheel.mc_wheel.btn_award.addEventListener(MouseEvent.CLICK, leftMenuHandler);
			
			animate_frame = 0;
			animate_index = -1;
			addEventListener(Event.ENTER_FRAME, frameHandler);			
			
			addChild(wheel);
		}
		
		private function leftMenuHandler(e:MouseEvent):void
		{
			var btn:SimpleButton = e.currentTarget as SimpleButton;
			
			switch(btn.name)
			{
				case "btn_beilv":
				case "btn_times":
				case "btn_award":
					switchToLeftMenu(btn.name);
					break;
				
			}
		}
		
		/**
		 * 切换菜单 
		 * @param menu
		 * 
		 */		
		private function switchToLeftMenu(menu:String):void
		{
			var btn:SimpleButton = wheel.mc_wheel[menu];
			var disp:DisplayObject = btn.overState;
			var i:int;
			
			if (leftSprite == null){
				leftSprite = new Bitmap();
				leftSprite.bitmapData = new BitmapData(disp.width, disp.height, true, 0x0);
				wheel.mc_wheel.addChildAt(leftSprite, wheel.mc_wheel.getChildIndex(wheel.mc_wheel.mc_btns));
			}
			
			leftSprite.bitmapData.draw(disp);			
			leftSprite.y = btn.y;
			
			wheel.mc_wheel.mc_beilv.visible = false;
			wheel.mc_wheel.mc_times.visible = false;
			wheel.mc_wheel.mc_award.visible = false;
			
			switch(menu)
			{
				case "btn_beilv":
					wheel.mc_wheel.mc_beilv.visible = true;
					for(i=0; i< 15; i++){
						if (info != null)
						wheel.mc_wheel.mc_beilv['txt_'+i].text = info['beilv'][i] + "x";
					}
					break;
				case "btn_times":
					wheel.mc_wheel.mc_times.visible = true;
					
					for(i =0; i<= 7; i++){
						wheel.mc_wheel.mc_times['value_'  + i].text = open_icons[i];
					}
					break;
				case "btn_award":
					wheel.mc_wheel.mc_award.visible = true;
					break;
			}
		}
		
		
		// 声音处理
		private function musicHandler(e:MouseEvent):void
		{
			SoundManager.getInstance().enable = SoundManager.getInstance().enable?false:true;
			
			if (SoundManager.getInstance().enable){
				wheel.mc_music.gotoAndStop(1);
			}else{
				trace("disable");
				wheel.mc_music.gotoAndStop(2);
			}
		}
		
		/**
		 *  点击图标下注
		 */	
		private function betHandler(e:MouseEvent):void
		{			
			var btn:SimpleButton = e.currentTarget as SimpleButton;
			var index:int = btn.name.split("_")[1];
			
			if (checkBetCash(1)){
				return;
			}
			
			SoundManager.getInstance().play("soundClick");
			
			wheel.mc_bet['Pet_' + index].text = parseInt(wheel.mc_bet['Pet_' + index].text) + 1;
			syncBet();
			
			betTimer = new Timer(20, 0);
			var t:int = 0;
			betTimer.addEventListener(TimerEvent.TIMER, function (e:TimerEvent):void{
				t++;
				if (t < 20)
					return;
				
				
				if (checkBetCash(1)){
					betTimer.stop();
					betTimer = null;
					return;
				}
				
				SoundManager.getInstance().play("soundClick");
				
				wheel.mc_bet['Pet_' + index].text = parseInt(wheel.mc_bet['Pet_' + index].text) + 1;
				syncBet();
			});
			
			betTimer.start();
		}
		
		private function stopbetHandler(e:MouseEvent):void
		{
			if (betTimer != null){
				betTimer.stop();
				betTimer = null;
			}
		}
		
		/**
		 * 重置 
		 * @param e
		 * 
		 */		
		private function resetHandler(e:MouseEvent):void
		{
			var i:int;
			
			for(i = 0; i<=7; i++){
				wheel.mc_bet['Pet_' + i].text = 0;
			}
			SoundManager.getInstance().play("soundClick");
			syncBet();
		}
		
		/**
		 * 全加 
		 * @param e
		 * 
		 */		
		private function betallHandler(e:MouseEvent):void
		{
			
			var btn:SimpleButton = e.currentTarget as SimpleButton;
			var num:int = btn.name.split("_")[1];
			
			var i:int;
			
			if (checkBetCash(num * 8))
				return;
			
			SoundManager.getInstance().play("soundClick");
			
			for(i = 0; i<=7; i++){
				wheel.mc_bet['Pet_' + i].text = parseInt(wheel.mc_bet['Pet_' + i].text) + num;
			}
			syncBet();
		}
		
		/**
		 * 同步下注到中间 
		 */		
		private function syncBet():void
		{
			var i:int;
			for(i = 0; i<=7; i++){
				wheel.mc_wheel['Pet_' + i].text = wheel.mc_bet['Pet_' + i].text;
			}
		}
		
		/**
		 * 开始游戏 
		 * @param e
		 * 
		 */		
		private function startHandler(e:MouseEvent):void
		{
			trace("start");
			if (checkBetCash()){
				return;
			}
			
			SoundManager.getInstance().play("soundBet");
			
			WindowManager.disableDisplayObject(wheel.btn_start, true);
			
			var vars:URLVariables = new URLVariables();
			
			var total:int = 0;
			for(var i:int = 0; i<=7; i++){
				vars['bet_' + i] = parseInt(wheel.mc_bet['Pet_' + i].text, 10);
				total += vars['bet_' + i];
			}
		
			animate_index = 0;
			animate_frame = 0;
			speed = 12;
			
			if (icon != -1){
				var lastMc:MovieClip = wheel.mc_wheel['wheel_' + icon];
				lastMc.gotoAndStop(1);
				icon = -1;
			}
			
			userinfo.cash -= total;
			wheel.mc_uinfo.txt_cash.text = userinfo.cash.toString();
			
			callMethod("bet", vars);
		}
		
		
		/**
		 * 设置投注结果 
		 * @param data 如果为null，则重置
		 * 
		 */		
		public function setResult(data:Object):void
		{
			Debug.dump(data);
			if (data == null){// reset
				reset();
			}else{
				betdata = data;
				userinfo.cash = data.cash;
				win = data.win;
				icon = data.icon;
				
				open_icons[data.winminicon]++;
			}			
		}
		
		
		/**
		 * 帧事件 
		 * @param e
		 * 
		 */		
		private function frameHandler(e:Event):void
		{
			if (animate_index == -1)return;
			
			animate_frame++;
			
			if (animate_frame % speed != 0)return;
			
			if (animate_frame < 120)
				speed--;
			
			if (speed <= 1) speed = 1;
						
			
			// 动画处理
			var mc:MovieClip = wheel.mc_wheel['wheel_' + animate_index];
			var premc:MovieClip;
			
			if (animate_index == 0){
				premc = wheel.mc_wheel.wheel_23;
			}else
				premc = wheel.mc_wheel['wheel_' + (animate_index-1)];
			
			if (premc != null)
				premc.gotoAndStop(1);
			
			mc.gotoAndStop(2);
			
			// 声音处理
			SoundManager.getInstance().play("soundDin");
			
			
			// 停止处理
			var stop_frame:int = 120+Math.random() * 50;
			if (icon != -1 && animate_frame > stop_frame){
				speed++;
			}
			if (speed > 10)speed = 10;
						
			
			// 动画停止
			if (speed == 10 && animate_index == icon){				
				wheel.mc_uinfo.txt_cash.text = userinfo.cash.toString();
				reset();
				
				if (win > 0){
					SoundManager.getInstance().play("soundWin");
					
					WinTip.show("恭喜你：\n开奖<font color=\"#FF6600\">"+betdata['name'] + "</font>\n获得奖金：" + win);
					
				}else{
					SoundManager.getInstance().play("sondLost");
				}
				
				
				// 中奖次数查看
				for(var i:int =0; i<= 7; i++){
					wheel.mc_wheel.mc_times['value_'  + i].text = open_icons[i];
				}
				
				// 最近开奖
				open_minname.unshift(betdata.minname);
				if (open_minname.length > 8){
					open_minname.splice(8);
				}
				for(i =0; i<= 7; i++){
					if (open_minname[i] != null)
					wheel.mc_wheel.mc_award['value_'+i].text = open_minname[i];
				}
				
				WindowManager.disableDisplayObject(wheel.btn_start, false);
				
				return;
			}
			
			animate_index++;
			
			if (animate_index == 24)
				animate_index = 0;
			
		}
		
		/**
		 * 重置 
		 * 
		 */		
		private function reset():void
		{			
			animate_index = -1;			
		}
		
		/**
		 * 检测cash 
		 * @return 
		 * 
		 */		
		private function checkBetCash(bet:int = 0):Boolean
		{
			var total:int=0,i:int;
			
			for(i = 0; i<=7; i++){
				total += parseInt(wheel.mc_bet['Pet_' + i].text);
			}
			
			var num:int;
			num = total + bet;
			
			if (num == 0 || total + bet > userinfo.cash || num > 1000){
				SoundManager.getInstance().play("soundAlert");
				
				if (num > 1000)
					wheel.mc_etip.outText.text = "最多下注\n1000元宝";
				else{
					wheel.mc_etip.outText.text = "元宝不足\n不能下注";
				}
				
				wheel.mc_etip.visible = true;
				
				var timer:uint = setTimeout(function ():void{
					wheel.mc_etip.visible = false;
					clearTimeout(timer);
				}, 3000);
				return true;
			}else{
				return false;
			}
		}
		
		/**
		 * 设置用户信息 
		 * 
		 */		
		public function setInfo(result:Object):void
		{
			wheel.mc_login.visible = false;
			wheel.mc_uinfo.visible = false;
			
			if (result != null && result.data != null)
				this.info = result.data;
			
			if (result == null || result['data']['uinfo'] == null){
				wheel.mc_login.visible = true;
				wheel.mc_login.iuser.text = "";
				wheel.mc_login.ipass.text = "";
				userinfo.reset();
			}else{
				wheel.mc_uinfo.visible = true;
				
				wheel.mc_uinfo.txt_username.text = result['data']['uinfo']['username'];
				wheel.mc_uinfo.txt_cash.text = result['data']['uinfo']['cash'];
				
				userinfo.setUserInfo(result.data.uinfo);
			}
			
			// 第一次设置倍率
			if (leftSprite == null){
				switchToLeftMenu("btn_beilv");
				if (info != null){
					wheel.mc_bet.txt_0.text = info.beilv[0] +"x";
					wheel.mc_bet.txt_1.text = info.beilv[9] +"x";
					wheel.mc_bet.txt_2.text = info.beilv[10] +"x";
					wheel.mc_bet.txt_3.text = info.beilv[7] +"x";
					wheel.mc_bet.txt_4.text = info.beilv[8] +"x";
					wheel.mc_bet.txt_5.text = info.beilv[12] +"x";
					wheel.mc_bet.txt_6.text = info.beilv[11] +"x";
					wheel.mc_bet.txt_7.text = info.beilv[14] +"x";
				}
			}
		}
		
		private function loginHandler(e:MouseEvent=null):void
		{
			var username:String = wheel.mc_login.iuser.text;
			var password:String = wheel.mc_login.ipass.text;
			
			callMethod("login", username, password);
		}
		
		private function keyHandler(e:KeyboardEvent):void
		{
			if (e.keyCode == Keyboard.ENTER){
				loginHandler();
			}
		}
		
		private function logoutHandler(e:MouseEvent):void
		{
			callMethod("logout");
		}
		
		private function regHandler(e:MouseEvent):void
		{
			trace("reg");
			callMethod("reg");
		}
		
		private function payHandler(e:MouseEvent):void
		{
			trace("pay");
			if (ExternalInterface.available)
				ExternalInterface.call("flashpay");
		}
	}	
}
/**
 "袁绍0", "孙权1", "大乔2", "夏侯惇3", "曹操4", "关羽5", "张飞6", "特殊7"
 */